package com.kay.springbootRESTful.service;

import com.kay.springbootRESTful.entity.Customer;
import com.kay.springbootRESTful.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @Author Kay
 * @Date: 2019/12/12 16:00
 */

@Service
public class CustomerService {

    @Autowired
    private CustomerRepository customerRepository;

    public Customer save(Customer customer) {
        return customerRepository.save(customer);
    }

    public ResponseEntity<Customer> update(Customer newCustomer) {
        return customerRepository.findById(newCustomer.getCustomerId()).map(customer -> {
            customerRepository.save(newCustomer);
            return ResponseEntity.ok(newCustomer);
        }).orElseThrow(() -> new RuntimeException("Customer [customerId =" + newCustomer.getCustomerId() + "] can't be found"));
    }

    public Customer findById(Integer customerId) {
        return customerRepository.findById(customerId).orElseThrow(() -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found"));
    }

    public Page<Customer> findAll(Pageable pageable) {
        return customerRepository.findAll(pageable);
    }

    public ResponseEntity<?> delete(Integer customerId) {
        return customerRepository.findById(customerId).map(customer -> {
            customerRepository.delete(customer);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new RuntimeException("Customer [customerId =" + customerId + "] can't be found"));
    }
}
